﻿using CRM.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;

namespace CRM.Controllers.Customer
{
    using CustomerModel = CRM.Models.Customer;

    [Route("client/[controller]")]
    public class ExportController : BaseController
    {
        private readonly MyDbContext _dbContext;
        private readonly UserManager<User> _userManager;

        private readonly int CustomerIsNotExist = 1;
        private readonly int CustomerExportParamsFail = 2;
        private readonly int CustomerExportNumFail = 3;

        public ExportController(MyDbContext dbContext, UserManager<User> userManager)
        {
            _dbContext = dbContext;
            _userManager = userManager;
        }

        [HttpPost(nameof(Customer))]
        public async Task<ResultStruct> Customer(Dictionary<string, List<int>> Data)
        {
            var Ids = Data["ID"];

            if (Ids.Count <= 0)
            {
                return Fail(new object(), "参数错误: Id", CustomerExportParamsFail);
            }

            var user = await _userManager.GetUserAsync(User);

            var List = await _dbContext.Customer
                .Where(m => Ids.Contains(m.Id) && m.OemId == user.OemId)
                .Include(m => m.Group)
                .Include(m => m.Source)
                .Include(m => m.Labels)
                .AsSplitQuery()
                .ToListAsync();

            if (List.Count <= 0)
            {
                return Fail(new object(), "客户不存在", CustomerIsNotExist);
            }

            if (List.Count != Ids.Count)
            {
                var num = Ids.Count - List.Count;
                return Fail(new object(), $"数据丢失：{num}条", CustomerExportNumFail);
            }

            if (user.SettingsObj.OnlyExportValidEmails)
            {
                // 过滤掉未验证邮箱客户
                List = List
                    .Where(c => c.EmailValidation == EmailValidationType.Validated ||
                                c.PersonalEmailValidation == EmailValidationType.Validated)
                    .ToList();
                
                foreach (var customer in List)
                {
                    if (customer.EmailValidation == EmailValidationType.Invalid)
                        customer.Email = string.Empty;
                
                    if (customer.PersonalEmailValidation == EmailValidationType.Invalid)
                        customer.PersonalEmail = string.Empty;
                }
            }
            
            

            return Complete(List, "获取成功");
        }

        protected ResultStruct Complete(object data = null, string message = "成功")
        {
            data = Newtonsoft.Json.JsonConvert.SerializeObject(data);
            return FormatResult(data, message, 1000);
        }

        protected ResultStruct Fail(object data = null, string message = "失败", int code = 1001)
        {
            var Base = 20000;
            data = Newtonsoft.Json.JsonConvert.SerializeObject(data);
            return FormatResult(data, message, Base + code);
        }

        private ResultStruct FormatResult(object data, string message, int code)
        {

            return new() { Data = data, Message = message, Code = code };
        }
    }
}
